package com.sxhuayuan.parking.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.sxhuayuan.parking.config.Constant;
import com.sxhuayuan.parking.dto.ParkFeeCacheBean;
import com.sxhuayuan.parking.service.ParkFeeCacheService;
import com.sxhuayuan.parking.service.RedisService;

@Component("parkFeeCacheServiceImpl")
public class ParkFeeCacheServiceImpl implements ParkFeeCacheService {

	public static final String PREFIX = "park_fee_";

	@Autowired
	RedisService redisService;

	@Override
	public void put(ParkFeeCacheBean bean) {
		int i = 0;
		boolean succ = false;
		String key = getKey(bean.getUniqueId());
		while (!succ && i++ < 3) {
			succ = redisService.updateString(key, JSON.toJSONString(bean), Constant.PARK_FEE_CACHE_TTL);
		}
	}

	@Override
	public ParkFeeCacheBean get(Long uniqueId) {
		String key = getKey(uniqueId);
		ParkFeeCacheBean bean = null;
		if (!StringUtils.isEmpty(key)) {
			bean = JSON.parseObject(redisService.getString(key), ParkFeeCacheBean.class);
		}
		return bean;
	}

	@Override
	public void remove(Long uniqueId) {
		String key = getKey(uniqueId);
		redisService.removeString(key);
	}

	private String getKey(Long uniqueId) {
		return PREFIX + uniqueId;
	}
}
